/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.controller;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import io.renren.annotation.Login;
import io.renren.common.redis.RedisUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.dto.WxLoginCodeDTO;
import io.renren.dto.LoginDTO;
import io.renren.dto.WxLoginPhoneDTO;
import io.renren.service.TokenService;
import io.renren.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.Map;

/**
 * 登录接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/api")
@Api(tags = "登录接口")
@AllArgsConstructor
public class ApiLoginController {
    private final UserService userService;
    private final TokenService tokenService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private WxMaService wxMaService;


    @PostMapping("login")
    @ApiOperation("登录")
    public Result<Map<String, Object>> login(@RequestBody LoginDTO dto) {
        //表单校验
        ValidatorUtils.validateEntity(dto);

        //用户登录
        Map<String, Object> map = userService.login(dto);

        return new Result().ok(map);
    }

    @Login
    @PostMapping("logout")
    @ApiOperation("退出")
    public Result logout(@ApiIgnore @RequestAttribute("userId") Long userId) {
        tokenService.expireToken(userId);
        return new Result();
    }

    @ApiOperation("获取微信授权信息")
    @ApiImplicitParam(name = "code",value = "前端授权登录后传来的code", required = true,paramType = "query")
    @RequestMapping(value = "/wechatSession", method = RequestMethod.POST)
    @ResponseBody
    public Result wechatSession(@RequestBody WxLoginCodeDTO dto) throws WxErrorException {
        //获取openId、unionid、session_key
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(dto.getCode());
        return new Result().ok(sessionInfo);
    }


    @ApiOperation("小程序手机号登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionKey", value = "sessionKey", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "encryptedData", value = "加密串", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "iv", value = "偏移量", paramType = "query", dataType = "string", required = true)
    })
    @RequestMapping(value = "/wechatLogin", method = RequestMethod.POST)
    @ResponseBody
    public Result wechatLogin(HttpServletRequest request,@RequestBody WxLoginPhoneDTO dto) {

        WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(dto.getSessionKey(), dto.getEncryptedData(), dto.getIv());
        return new Result().ok(phoneInfo.getPurePhoneNumber());
    }
}